<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="公告标题" prop="noticeTitle">
        <el-input
            v-model="queryParams.noticeTitle"
            placeholder="请输入公告标题"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="noticeType">
        <el-select v-model="queryParams.noticeType" placeholder="公告类型" clearable style="width: 200px">
          <el-option
              v-for="dict in sys_notice_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['system:notice:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:notice:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <draggable
        v-model="noticeList"
        item-key="noticeId"
        @end="onEnd"
        handle=".drag-handle"
    >
      <template #item="{ element }">
        <el-table
            :data="[element]"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            :show-header="false"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" align="center" prop="noticeId" width="100" />
          <el-table-column
              label="公告标题"
              align="center"
              prop="noticeTitle"
              :show-overflow-tooltip="true"
          />
          <el-table-column label="公告类型" align="center" prop="noticeType" width="100">
            <template #default="scope">
              <dict-tag :options="sys_notice_type" :value="scope.row.noticeType" />
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" width="100">
            <template #default="scope">
              <dict-tag :options="sys_notice_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="100">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:notice:edit']"
              >修改</el-button>
              <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['system:notice:remove']"
              >删除</el-button>
              <el-button
                  link
                  type="primary"
                  icon="Rank"
                  class="drag-handle"
              >拖拽</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </draggable>

    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公告标题" prop="noticeTitle">
              <el-input v-model="form.noticeTitle" placeholder="请输入公告标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公告类型" prop="noticeType">
              <el-select v-model="form.noticeType" placeholder="请选择" style="width: 100%">
                <el-option
                    v-for="dict in sys_notice_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
                v-for="dict in sys_notice_status"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容">
          <el-input
              type="textarea"
              :rows="6"
              placeholder="请输入内容"
              v-model="form.noticeContent"
          />
        </el-form-item>

        <el-form-item label="附件上传">
          <div class="upload-container">
            <el-upload
                ref="uploadRef"
                v-model:file-list="fileList"
                :action="uploadUrl"
                :auto-upload="false"
                :data="dataPath"
                :disabled="formLoading"
                :limit="2"
                :on-change="handleFileChange"
                :on-error="submitFormError"
                :on-exceed="handleExceed"
                :on-success="submitFormSuccess"
                :http-request="httpRequest"
                accept=".jpg, .png, .gif"
                drag
                class="upload-area"
            >
              <div class="upload-content">
                <el-icon class="upload-icon"><Upload /></el-icon>
                <div class="upload-text">
                  将文件拖到此处，或 <em>点击上传</em>
                </div>
                <div class="upload-tip">
                  提示：仅允许导入 jpg、png、gif 格式文件！最多上传2个文件
                </div>
              </div>
            </el-upload>

            <!-- 预览图片列表 -->
            <div class="image-list" v-if="fileList.length > 0">
              <div v-for="file in fileList" :key="file.uid" class="image-item">
                <img :src="file.url" :alt="file.name" class="preview-image">
                <div class="image-actions">
                  <el-button type="primary" link @click="handlePictureCardPreview(file)">
                    <el-icon><ZoomIn /></el-icon>
                  </el-button>
                  <el-button type="danger" link @click="handleRemove(file)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <!-- 图片预览 -->
      <el-image-viewer
          v-if="dialogVisible"
          :url-list="dialogImageUrl"
          @close="dialogVisible = false"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Notice">
import {ref, reactive, toRefs, watch, unref, nextTick, getCurrentInstance} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Upload, ZoomIn, Delete } from '@element-plus/icons-vue';
import request from '@/utils/request';
import { parseTime } from '@/utils/ruoyi';
import { getToken } from '@/utils/auth';
import { updateFile, submitImageIds } from '@/api/infra/file';
import { listNotice, delNotice, addNotice, updateNotice, getNotice } from '@/api/system/notice';
import DictTag from '@/components/DictTag';
import { useUpload } from '@/components/UploadFile/src/useUpload';
import draggable from 'vuedraggable'; // 引入 vuedraggable

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();
const { sys_notice_status, sys_notice_type } = proxy.useDict("sys_notice_status", "sys_notice_type");
const dialogVisible = ref(false);
const dialogImageUrl = ref([]);
const noticeList = ref([]);
const disabled = ref(true); // 确保 disabled 是响应式数据
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const firstNoticeOrder = ref(null); // 创建一个 ref 来存储第一个数据的 noticeOrder
const formLoading = ref(false); // 表单的加载中
const fileList = ref([]); // 文件列表
const dataPath = ref({ path: '' });
const uploadRef = ref();
const { uploadUrl, httpRequest } = useUpload();

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: "noticeOrder",
    noticeTitle: undefined,
    createBy: undefined,
    status: undefined
  },
  rules: {
    noticeTitle: [{ required: true, message: "公告标题不能为空", trigger: "blur" }],
    noticeType: [{ required: true, message: "公告类型不能为空", trigger: "change" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 处理上传的文件发生变化 */
const handleFileChange = (file, fileList) => {
  // 更新 fileList
  fileList.value = fileList;
};

/** 提交表单 */
const submitFileForm = () => {
  return new Promise((resolve, reject) => {
    const noticeId = form.value.noticeId; // 获取公告ID

    const uploadPromises = fileList.value.map(async (fileItem, index) => {
      if (fileItem.id) {
        // 如果文件已经有ID，说明是已上传的文件，不需要重新上传
        return;
      }

      const file = fileItem.raw; // 假设 fileItem.raw 是文件对象
      if (!file) {
        // 如果没有文件对象，说明是已上传的文件，不需要重新上传
        return;
      }

      const path = file.name; // 假设文件路径为文件名

      const data = new FormData();
      data.append('file', file);
      data.append('path', path);

      try {
        const response = await updateFile(data);
        console.log('文件上传结果:', response);
        if (response.code === 200) {
          ElMessage.success('文件上传成功');
          // 更新 fileList 中的文件对象，添加文件ID
          fileList.value[index].id = response.data.id; // 假设后端返回的文件ID字段为 id
        } else {
          ElMessage.error('文件上传失败: ' + response.message);
          reject();
        }
      } catch (error) {
        console.error('上传文件时发生错误:', error);
        ElMessage.error('文件上传失败');
        reject();
      }
    });

    Promise.all(uploadPromises)
        .then(() => {
          resolve();
        })
        .catch((error) => {
          console.error('文件上传过程中发生错误:', error);
          reject();
        });
  });
};

/** 文件上传成功处理 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
/** 文件上传成功处理 */
const submitFormSuccess = () => {
  // 清理
  open.value = false;
  formLoading.value = false;
  unref(uploadRef)?.clearFiles();
  // 提示成功，并刷新
  ElMessage.success('文件上传成功');
  emit('success');
};

/** 上传错误提示 */
const submitFormError = () => {
  ElMessage.error('上传失败，请您重新上传！');
  formLoading.value = false;
};

/** 重置表单 */
const resetForm = () => {
  // 重置上传状态和文件
  formLoading.value = false;
  uploadRef.value?.clearFiles();
};

/** 文件数超出提示 */
const handleExceed = (files, fileList) => {
  ElMessage.warning(`当前限制选择 2 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
};

const handleRemove = (file) => {
  // 通过 uid 移除 fileList 中对应的文件对象
  fileList.value = fileList.value.filter(item => item.id !== file.id);
  ElMessage.success('文件已删除'); // 修复：使用 ElMessage 替代 message
};

const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = [file.url];
  dialogVisible.value = true;
};

function onEnd(event) {
  const { newIndex, oldIndex } = event;
  const movedItem = noticeList.value.splice(newIndex, 1)[0];
  noticeList.value.splice(newIndex, 0, movedItem);

  noticeList.value.forEach((item, index) => {
    console.log('Moving item:', item.noticeId);
    console.log('Moving index:', index);
    item.noticeOrder = firstNoticeOrder.value + index;
  });

  // 准备更新顺序的数据
  const orderData = noticeList.value.map((item, index) => ({
    noticeId: item.noticeId,
    noticeOrder: item.noticeOrder
  }));

  // 打印发送的数据
  console.log('Sending order data:', orderData);

  // 更新顺序到后端（假设有一个 updateOrder 接口）
  updateOrder(orderData).then(response => {
    ElMessage.success('顺序更新成功');
  }).catch(error => {
    console.error('顺序更新失败:', error);
    ElMessage.error('顺序更新失败');
  });
}

function updateOrder(orderData) {
  return request({
    url: '/system/notice/updateOrder',
    method: 'put',
    data: orderData
  });
}

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listNotice(queryParams.value).then(response => {
    noticeList.value = response.rows;
    total.value = response.total;
    loading.value = false;

    // 更新 firstNoticeOrder 变量
    if (noticeList.value.length > 0) {
      firstNoticeOrder.value = noticeList.value[0].noticeOrder;
      console.log('noticeOrder:', noticeList.value[0].noticeOrder);
    } else {
      firstNoticeOrder.value = null; // 如果没有数据，设置为 null
    }
    console.log('noticeList:', noticeList.value);
  }).catch(error => {
    console.error('获取公告列表失败:', error);
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    noticeId: undefined,
    noticeTitle: undefined,
    noticeType: undefined,
    noticeContent: undefined,
    status: "0"
  };
  proxy.resetForm("noticeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.noticeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加公告";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const noticeId = row.noticeId || ids.value;
  getNotice(noticeId).then(response => {
    form.value = response.data;
    // 获取已上传的图片信息
    getNoticeImages(noticeId).then(imageResponse => {
      fileList.value = imageResponse.data.map(image => ({
        name: image.name,
        url: image.url,
        uid: image.id, // 使用文件的 uid
        id: image.id // 假设后端返回的图片ID字段为 id
      }));
    });
    open.value = true;
    title.value = "修改公告";
  });
}

// 获取公告的图片信息
function getNoticeImages(noticeId) {
  return request({
    url: `/infra/file/notice/images/${noticeId}`,
    method: 'get'
  });
}

/** 提交表单 */
const submitForm = async () => {
  try {
    await submitFileForm(); // 等待文件提交完成
    await nextTick(); // 确保 DOM 更新完成
    proxy.$refs["noticeRef"].validate(async valid => {
      if (valid) {
        const noticeId = form.value.noticeId; // 获取公告ID

        // 提取 fileList 中的所有文件项的 id
        form.value.imageIds = fileList.value.map(file => file.id).filter(id => id); // 提取图片ID列表

        if (noticeId != undefined) {
          // 检查 form.value.imageIds 是否有值
          if (form.value.imageIds && form.value.imageIds.length > 0) {
            await submitImageIds(noticeId, form.value.imageIds);
          } else {
            console.log('没有图片ID需要提交');
          }
          await updateNotice(form.value); // 等待更新公告完成
          proxy.$modal.msgSuccess("修改成功");
        } else {
          const noticeId1 = await addNotice(form.value);
          if (noticeId1.data === undefined) {
            throw new Error('addNotice 没有返回有效的 noticeId');
          }

          // 检查 form.value.imageIds 是否有值
          if (form.value.imageIds && form.value.imageIds.length > 0) {
            await submitImageIds(noticeId1.data, form.value.imageIds);
          } else {
            console.log('没有图片ID需要提交');
          }
          // 其他后续操作
          proxy.$modal.msgSuccess("新增成功");
        }
        open.value = false;
        getList();
      }
    });
  } catch (error) {
    console.error('提交表单时出错:', error);
  }
};

/** 删除按钮操作 */
function handleDelete(row) {
  const noticeIds = row.noticeId || ids.value;
  proxy.$modal.confirm('是否确认删除公告编号为"' + noticeIds + '"的数据项？').then(function() {
    return delNotice(noticeIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

getList();
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.drag-handle {
  cursor: move;
}

/* 弹窗样式优化 */
.notice-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.notice-form {
  margin-bottom: 0;
}

.notice-form :deep(.el-form-item__label) {
  font-weight: 500;
}

.notice-form :deep(.el-input),
.notice-form :deep(.el-select) {
  width: 100%;
}

.notice-form :deep(.el-textarea__inner) {
  min-height: 120px;
  font-family: inherit;
}

.upload-container {
  width: 100%;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 4px;
}

.upload-area {
  width: 100%;
}

.upload-area :deep(.el-upload) {
  width: 100%;
}

.upload-area :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area :deep(.el-upload-dragger:hover) {
  border-color: #409eff;
}

.upload-content {
  text-align: center;
  padding: 20px;
}

.upload-icon {
  font-size: 48px;
  color: #909399;
  margin-bottom: 16px;
}

.upload-text {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.upload-text em {
  color: #409eff;
  font-style: normal;
  cursor: pointer;
}

.upload-tip {
  font-size: 12px;
  color: #f56c6c;
  margin-top: 8px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 16px;
}

.image-item {
  position: relative;
  width: 148px;
  height: 148px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-textarea__inner) {
  font-family: inherit;
}
</style>
